package com.nega.modules.controller;

import com.nega.commons.model.Message;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Garcia
 * @CreateDate: 2019/5/9 0:24
 * @Description: what it is class?
 */

@Controller
@RequestMapping("/")
@Slf4j
public class IndexController {

    @RequestMapping("index")
    public String index(Model model){
        return "index";
    }

    @PostMapping("login")
    @ResponseBody
    public Message login(String username,String password){

        if (StringUtils.isBlank(username)||StringUtils.isBlank(password)){
            return Message.error("账号或密码不能为空");
        }

        Subject subject = SecurityUtils.getSubject();
        try{
            subject.login(new UsernamePasswordToken(username, password));
            Map<String,Object> params = new HashMap<>();
            params.put("token","fjeifjiefgue");
            return Message.success(params);
        }catch(UnknownAccountException e){
            log.error("账号不存在");
            return Message.error("账号或密码错误");
        }catch (IncorrectCredentialsException e){
            log.error("密码错误");
            return Message.error("账号或密码错误");
        }catch (DisabledAccountException e){
            log.error("账号未激活");
            return Message.error("账号未激活");
        }catch (Exception e){
            log.error("系统异常",e);
            return Message.error("系统异常");
        }
    }

    @GetMapping("menus")
    @ResponseBody
    public Message menus(){
        List<String> menu = new ArrayList<>();
        menu.add("/memuser/manager");
        return Message.success(menu);
    }

    @PostMapping("logout")
    @ResponseBody
    public Message logout(){
        SecurityUtils.getSubject().logout();
        return Message.success();
    }
}
